/*
 * @Author: silence
 * @Date: 2023-08-18 10:03:29
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-10-18 14:22:49
 * @Description: 配网第二步：设置家里可用2.4GWi-Fi
 */
import 'dart:io';

import 'package:ems_neutral_app/pages/DeviceNetworking/DNLinkDeviceWifiPage.dart';
import 'package:ems_neutral_app/pages/Mine/Language/SilLocalizations/SilLocalizations.dart';
import 'package:ems_neutral_app/utils/router/ARouter.dart';
import 'package:ems_neutral_app/utils/toast/SilToastExtends.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sil_base_widget_package/sil_base_widget_package.dart';
import 'package:sil_utils_package/sil_utils_package.dart';

import '../../base/SilScaffold.dart';
import '../../common/Method/CommonMethod.dart';
import '../../common/widgets/cubitWidget/SubmitBtn.dart';
import '../../utils/color/ColorUtils.dart';
import 'Controller/DeviceNetworkingController.dart';
import 'View/DeviceNetworkingItem.dart';

class DNSetLocalWifiPage extends StatefulWidget {
  const DNSetLocalWifiPage({super.key});

  @override
  State<DNSetLocalWifiPage> createState() => _DNSetLocalWifiPageState();
}

class _DNSetLocalWifiPageState extends State<DNSetLocalWifiPage>
    with WidgetsBindingObserver {
  DeviceNetworkingController _controller =
      Get.put(DeviceNetworkingController());

  /// wifi名称
  String? _ssid;

  /// wifi密码
  String? _pwd;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this); // 注册监听器

    getSsid();
  }

  /// 处理从设置返回
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed && this.mounted) {
      getSsid();
    }
    super.didChangeAppLifecycleState(state);
  }

  /// 获取设备名称
  getSsid() {
    _controller.getConnectedWifiSsid().then((value) {
      setState(() {
        _ssid = value;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return SilScaffold(
      title: LangOf(context)?.deviceNetworking?.setWifi, //'设置Wi-Fi',
      body: mainWidget(),
    );
  }

  mainWidget() {
    return Column(
      children: [
        Expanded(child: contentView()),
        bottomBtn(),
      ],
    );
  }

  /// 内容
  contentView() {
    return ListView(children: [
      Padding(padding: EdgeInsets.only(top: 20.w)),

      /// 提示文字
      SilText(
        LangOf(context)
            ?.deviceNetworking
            ?.setWifiPrompt, //'选择2.4GHz Wi-Fi网络并输入密码',
        color: ColorUtils.color_font_main,
        fontSize: 14.sp,
        maxLines: 0,
        lineHeight: 1.5.w,
      ),

      /// 图片
      SilImage(
        'imgs/device_net/device_net_local_wifi_prompt.png',
        width: 250.w,
        height: 240.w,
        fit: BoxFit.contain,
        margin: EdgeInsets.only(top: 50.w),
      ),

      Padding(padding: EdgeInsets.only(top: 50.w)),

      /// 设置家中wifi和密码
      wifiSsidView(),
      wifiPwdView(),
    ]);
  }

  /// 设置家中wifi SSID
  wifiSsidView() {
    return DeviceNetworkingItem(
        margin: EdgeInsets.all(0),
        title: _ssid,
        leftImgPath: 'imgs/device_net/device_net_wifi.png',
        leftImgHeight: 18.w,
        leftImgWidth: 24.w,
        rightView: Container(
            width: 30.w,
            alignment: Alignment.centerRight,
            child: SilButton(
              imgPath: "imgs/device_net/device_net_change.png",
              imgHeight: 16.w,
              imgWidth: 16.w,
              height: 24.w,
              width: 24.w,
              onTapFunc: () async {
                /// wifi开关打开，并且有定位权限
                bool isLocationEnabled =
                    await _controller.checkWifiSwitchAndLocalPower(context);
                if (isLocationEnabled) {
                  _controller.openWifiSettings();
                }
              },
            )));
  }

  /// 设置家中wifi PWD
  wifiPwdView() {
    return DeviceNetworkingItem(
      margin: EdgeInsets.all(0),
      leftImgPath: 'imgs/device_net/device_net_pwd_flag.png',
      leftImgHeight: 18.w,
      leftImgWidth: 16.w,
      middleView: SilTextField(
          isObscure: true,
          hintText:
              LangOf(context)?.deviceNetworking?.inputWifiPwd, //'请输入Wi-Fi密码',
          onValid: (valid, value) {
            _pwd = value;
          },
          interface: SilFormattersPwd()),
    );
  }

  /// 底部按钮
  bottomBtn() {
    return SubmitBtn(
      margin: EdgeInsets.only(
          top: 10.w, bottom: MediaQuery.of(context).padding.bottom + 10.w),
      title: LangOf(context)?.deviceNetworking?.nextStep, //'下一步',
      onTapFunc: () => checkHandler(),
    );
  }

  /// 这里做一下验证操作
  checkHandler() async {
    // 隐藏键盘
    globalTextFieldDismiss(context);

    /// 后续处理
    /// 1wifi名称、密码不能为空
    if (SilTools.stringIsEmpty(_ssid)) {
      //SilToast.show("Wi-Fi名称不能为空");
      SilToastExtends.toastMsg(LangOf(context)?.deviceNetworking?.noWifiName);
      return;
    }

    if (SilTools.stringIsEmpty(_pwd)) {
      //SilToast.show("Wi-Fi密码不能为空");
      SilToastExtends.toastMsg(LangOf(context)?.deviceNetworking?.noWifiPwd);
      return;
    }

    /// 3检查wifi是否可以联网
    _controller.ssid = _ssid;
    _controller.pwd = _pwd;

    /// 2检查wifi是否2.4G（android）
    if (Platform.isAndroid) {
      bool is24Ghz = await _controller.checkWifiGHZ();
      if (is24Ghz == false) {
        wifiIs24GhzPrompt();
        return;
      }
      ARoute.gotoPage(context, DNLinkDeviceWifiPage());
    } else {
      /// 提示使用2.4Gwifi进行配网（iOS）
      wifiIOSPrompt();
    }
  }

  wifiIs24GhzPrompt() {
    SilAlertDialog.showAlertDialog(
        context,
        SilAlertDialogData(
            content: LangOf(context)
                ?.deviceNetworking
                ?.no5GHzWifi, //"当前选择的是5GHz Wi-Fi，设备不支持，请更换为2.4GHz Wi-Fi网络",
            confrimButtonTitle: LangOf(context)?.aboutUs?.btnText //"我知道了",
            ),
        confrimFunc: () {});
  }

  /// iOS提示
  wifiIOSPrompt() {
    SilAlertDialog.showAlertDialog(
        context,
        SilAlertDialogData(
          content: LangOf(context)
              ?.deviceNetworking
              ?.netConfirmPrompt, //"请确认当前选择的是2.4GHz Wi-Fi网络",
          confrimButtonTitle: LangOf(context)?.deviceNetworking?.goOn, //"继续",
          cancelButtonTitle:
              LangOf(context)?.deviceNetworking?.switchNet, //"去切换",
        ), confrimFunc: () {
      ARoute.gotoPage(context, DNLinkDeviceWifiPage());
    }, cancelFunc: () async {
      /// wifi开关打开，并且有定位权限
      bool isLocationEnabled =
          await _controller.checkWifiSwitchAndLocalPower(context);
      if (isLocationEnabled) {
        _controller.openWifiSettings();
      }
    });
  }
}
